import React, { useEffect, useRef, useState } from 'react';
import { Button, Input, Modal, message } from 'antd';
import { getConversationList } from '@/api/conversationApi'
import dayjs from 'dayjs'
import io from 'socket.io-client'
import './modal.css'
import { updUser } from '@/api/usersApi'

const App = (prpos: any) => {
  const { isModalOpen, setIsModalOpen, modelPrpos: { userInfo }, refreshList } = prpos
  const [data, setData] = useState([] as any);
  const [word, setWord] = useState('');
  const [newMessage, setNewMessage] = useState(false);

  const socket = io("http://120.55.191.224:3000");//与服务器电脑连接的网络ip一致(注:端口号与webSocket的后端服务端口号一致)
  const Init = async () => {
    await updUser({ _id: userInfo._id, newMessage: false })
    const res = await getConversationList({ userID: userInfo['_id'], admin: 'admin' })
    if (res?.flag) { setData(res.data) }
  }
  useEffect(() => {
    newMessage && setNewMessage(false);
    isModalOpen && Init()
  }, [isModalOpen, newMessage])
  useEffect(() => {
    socket.on('errey', async (res) => {
      // 有新消息
      setNewMessage(true)
      // 刷新用户列表红点标记
      await refreshList()
      // 刷新会话记录
      setData(res.data)
      console.log("已收到客户端发送的消息");
    });
  }, [])
  // 发送信息
  const send = async () => {
    if (socket.id) {
      message.success('发送成功');
    } else {
      message.error('服务器未响应');
      return
    }
    socket.emit('sendMessage', {
      admin: 'admin',
      userID: userInfo['_id'],
      name: userInfo.name,
      word,
      type: 1,
    }, (res: any) => {
      console.log(res);
      setWord('')
    });
  };
  //隔一分钟以上再提交时间
  const timeShow = (val: any, i: any) => {
    if (!data.length) return ''
    const lastVal = data[i - 1]?.time
    const isChange = dayjs(lastVal).format('YYYY-MM-DD HH-mm') !== dayjs(val).format('YYYY-MM-DD HH-mm')
    return isChange
  }
  const onCancel = () => {
    // socket.emit('disconnection',  (res: any) => {
    //   console.log(res);
    // });
    setIsModalOpen(false)
  }
  return (
    <>
      <Modal title='会话记录' open={isModalOpen} onCancel={onCancel} footer={null} forceRender>
        <div className='content'>
          {data.length ? data.map((v: any, i: any) => {
            return <div key={v._id}><div className='time'>{v.time && timeShow(v.time, i) ? dayjs(v.time).format('MM-DD HH:mm') : ""}</div>
              {v.type === 1 ? <div className='rig'><img src="/imgs/customer.png" alt="" height={30} width={30} /><p>{v.word}</p></div> : <div className='lef'><img src="/imgs/picture.jpg" alt="" height={30} width={30} /><p>{v.word}</p></div>}
            </div>
          }) : <p className='noData'>暂无会话记录</p>}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Input placeholder="请输入内容" value={word} onChange={e => setWord(e.target.value)} />&emsp;<Button type="primary" onClick={send}>发送</Button>
        </div>
      </Modal>
    </>
  );
};

export default App;